package org.example.tinyurl.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.example.util.ContextHolderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * @author: zk
 * @date: 2023/6/21 18:49
 * 自己实现分库策略
 */
public class MyDBPreciseAlgorithm implements PreciseShardingAlgorithm<Long> {

    private static final Logger logger = LoggerFactory.getLogger(MyDBPreciseAlgorithm.class);

    @Override
    public String doSharding(Collection<String> databases, PreciseShardingValue<Long> shardingValue) {
        Long id = ContextHolderUtil.idHolder.get();
        Long suffix = id % 4 + 1;

        String db = "db" + suffix;
        if (databases.contains(db)) {
            return db;
        }
        logger.error("找不到数据库，suffix: {}", suffix);
        throw new UnsupportedOperationException("找不到数据库");
    }
}
